package com.example.safeassistan.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.adapter.RiskPointAdapter;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.model.RiskPointListSearchModel;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.example.safeassistan.common.MethodUtils.getUserId;
import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class RiskPointList extends BaseActivity implements View.OnClickListener {
    private RiskPointAdapter adapter;
    private RecyclerView rcView;
    private LinearLayout llNodata;
    private List<RiskPointListSearchModel.ResultDTO.RecordsDTO> data;
    private int selectType=1;//搜索类型  1 我的 2 部门
    private SmartRefreshLayout refresh;
    private EditText etText;
    private TextView tvSearch;
    private  int currentPage=1;
    private int count=0;


    private String riskPointName="";

    public static void actionStart(Context context,int selectType) {
        Intent intent = new Intent(context, RiskPointList.class);
        intent.putExtra("selectType",selectType);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.risk_point_list;
    }

    @Override
    protected void initView() {
        setTitleText("搜索风险点");
        selectType=getIntent().getIntExtra("selectType",1);
        rcView=findViewById(R.id.rcView);
        refresh=findViewById(R.id.refresh);
        llNodata=findViewById(R.id.llNodata);
        tvSearch=findViewById(R.id.tvSearch);
        etText=findViewById(R.id.etText);
        etText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                riskPointName=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvSearch.setOnClickListener(this);
        setView();
        getData();
    }

    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_RIGHT_IMG;
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));
            map.put("riskPointName",riskPointName);
            map.put("selectType",String.valueOf(selectType));//选择类型 1 我的 2 部门
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(RiskPointList.this).doPost(UrlConstants.getRiskList, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), RiskPointListSearchModel.class);
                        if (obj instanceof RiskPointListSearchModel) {
                            RiskPointListSearchModel model=(RiskPointListSearchModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    data=model.getResult().getRecords();
                                    adapter=new RiskPointAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(RiskPointList.this));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            RiskPointDetail.actionStart(getContext(),data.get(position).getId(),1,"0");
                                        }
                                    });
                                } else {
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(RiskPointList.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvSearch:
                getData();
                break;
        }
    }
}